//
//  BVBMKMapViewController.m
//  BuyVegetables1
//
//  Created by 叶思超 on 15/11/2.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVBMKMapViewController.h"
#import "BVConst.h"
#import "BVBMKAddressCell.h"
#import "UIView+Extension.h"

@interface BVBMKMapViewController () <BMKLocationServiceDelegate, BMKMapViewDelegate, BMKPoiSearchDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
@property (nonatomic, strong) UITextField *detailAddressF;
/**
 *  创建百度地图地位服务
 */
@property (nonatomic, strong) BMKLocationService *locationService;
/**
 *  创建百度地图
 */
@property (nonatomic, strong)  BMKMapView *mapView;
/**
 *  poi搜索
 */
@property (nonatomic, strong) BMKPoiSearch *poiSearch;
/**
 *  当前页
 */
@property (nonatomic, assign) int currentPage;
/**
 *  添加tableview
 */
@property (nonatomic, strong) UITableView *tableView;
/**
 *  存放所有地址信息
 */
@property (nonatomic, strong) NSMutableArray *address;
/**
 *  输入框
 */
@property (nonatomic, strong) UITextField *inputField;
/**
 *  工具条
 */
@property (nonatomic, strong) UIView *toolView;
/**
 *  指示线
 */
@property (nonatomic, weak) UIView *accessoryLine;
/**
 *  当前经纬度
 */
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
/**
 *  搜索关键字
 */
@property (nonatomic, copy) NSString *searchKey;
/**
 *  按照条件搜索
 */
@property (nonatomic, strong) UITableView *searchTabelView;
@end

@implementation BVBMKMapViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.frame = CGRectMake(0, CGRectGetMaxY(self.toolView.frame), BVScreenW, BVScreenH - CGRectGetMaxY(self.toolView.frame));
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 60;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)address {
    if (!_address) {
        _address = [NSMutableArray array];
    }
    return _address;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locationService.delegate = self;
    _poiSearch.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locationService.delegate = nil;
    
    [self stopLocate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 设置导航栏
    [self setupNav];
    
    // 开启定位
    [self setupBMK];
}

#pragma mark -- 设置工具条
- (void)setupTool {
    self.toolView = [[UIView alloc] init];
    self.toolView.frame = CGRectMake(0, CGRectGetMaxY(self.mapView.frame), BVScreenW, 40);
    [self.view addSubview:self.toolView];
    
    NSArray *titleArray = @[@"小区", @"写字楼", @"学校"];
    
    CGFloat titleW = BVScreenW / 3;
    for (NSInteger i = 0; i < titleArray.count; i++) {
        UIButton *button = [[UIButton alloc] init];
        button.x = titleW * i;
        button.y = 0;
        button.width = titleW;
        button.height = 40;
        button.tag = i;
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.toolView addSubview:button];
        
        // 添加指示线
        if (0 == i) {
            UIView *accessoryLine = [[UIView alloc] init];
            accessoryLine.frame = CGRectMake(0, 38, titleW, 2);
            accessoryLine.backgroundColor = BVBaseOrangeColor;
            [button addSubview:accessoryLine];
            self.accessoryLine = accessoryLine;
            
            // 默认选中
            [self buttonClick:button];
        }
    }
    
    // 分割线
    UIView *separatorLine = [[UIView alloc] init];
    separatorLine.frame = CGRectMake(0, 39, BVScreenW, 1);
    separatorLine.backgroundColor = [UIColor blackColor];
    separatorLine.alpha = 0.15;
    [self.toolView addSubview:separatorLine];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.address.count == 0) {
        return 0;
    }
    return self.address.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建cell
    BVBMKAddressCell *cell = [BVBMKAddressCell cell];
    
    cell.poiInfo = self.address[indexPath.row];
    
    return cell;
}

#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(mapViewController:poiInfo:)]    ) {
        [self.delegate mapViewController:self poiInfo:self.address[indexPath.row]];
        ROOTNAVPOP
    }
}

#pragma mark -- 初始化百度地图
- (void)setupBMK {
    // 添加地图控件
    BMKMapView *mapView = [[BMKMapView alloc] init];
    mapView.showsUserLocation = NO;//先关闭显示的定位图层
    mapView.userTrackingMode = BMKUserTrackingModeNone;
    mapView.showsUserLocation = YES;
    mapView.frame = CGRectMake(0, 64, BVScreenW, 240);
    mapView.zoomLevel = 16;
    [self.view addSubview:mapView];
    self.mapView = mapView;
    
    
    // 开启定位
    self.locationService = [[BMKLocationService alloc] init];
    // 设置定位精确度，默认：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    // 指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    [self.locationService startUserLocationService];
}

#pragma mark - 停止定位
- (void)stopLocate {
    [self.locationService stopUserLocationService];
    _mapView.showsUserLocation = NO;
}

#pragma mark - 定位函数
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    [_mapView updateLocationData:userLocation];
    
    self.coordinate = userLocation.location.coordinate;
    
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
    // 设置工具栏
    [self setupTool];

    [self.locationService stopUserLocationService];
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error {
    NSLog(@"location error");
}

- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 关键字检索
- (void)initPoiSearchWith:(CLLocationCoordinate2D)coordinate {
    //初始化检索对象
    _poiSearch =[[BMKPoiSearch alloc]init];
    _poiSearch.delegate = self;
    //发起检索
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
    option.pageIndex = _currentPage;
    option.pageCapacity = 20;
    option.radius = 2000;
    NSLog(@"%f   %f",coordinate.longitude,coordinate.latitude);
    option.location = coordinate;
    option.keyword = self.searchKey;
    BOOL flag = [_poiSearch poiSearchNearBy:option];
    
    if(flag) {
        NSLog(@"周边检索发送成功");
    }
    else {
        NSLog(@"周边检索发送失败");
    }
}

#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error {
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    // 移除数组
    [self.address removeAllObjects];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            [self.address addObject:poi];
        }
        
        if (self.inputField.text.length == 0) {
            [self.tableView reloadData];
        } else if (![self.inputField.text isEqualToString:@"小区/写字楼/学校"]) {
            [self.searchTabelView reloadData];
        }
        [_mapView showAnnotations:annotations animated:YES];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    } else {
        // 各种情况的判断。。。
    }
}

#pragma mark -- button点击事件
- (void)buttonClick:(UIButton *)button {
    self.accessoryLine.x = button.tag * (BVScreenW / 3);
    
    // 搜索关键字
    self.searchKey = button.currentTitle;
    
    // poi搜索
    [self initPoiSearchWith:self.coordinate];
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
    
    // 输入框
    self.inputField = [[UITextField alloc] init];
    self.inputField.frame  = CGRectMake(44, 35, BVScreenW - 44 * 2, 35);
    self.inputField.backgroundColor = [UIColor whiteColor];
    self.inputField.placeholder = @" 小区/写字楼/学校";
    [self.inputField setValue:BVBaseTextLightBlackColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.inputField setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    self.inputField.textColor = BVBaseTextLightBlackColor;
    self.inputField.layer.cornerRadius = 4;
    self.inputField.layer.masksToBounds = YES;
    self.inputField.delegate = self;
    self.navigationItem.titleView = self.inputField;
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // 清空数组
    [self.address removeAllObjects];
    
    _searchTabelView = [[UITableView alloc] init];
    _searchTabelView.frame = CGRectMake(0, 64, BVScreenW, BVScreenH - 216 - 64);
    _searchTabelView.dataSource = self;
    _searchTabelView.delegate = self;
    _searchTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _searchTabelView.rowHeight = 60;
    [self.view addSubview:_searchTabelView];

    // 取消遮盖
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelClick)];
    
    // 通知键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.inputField];
}

#pragma mark -- textChange
- (void)textChange {

    if (self.inputField.text.length == 0) {
        self.navigationItem.rightBarButtonItem.title = @"取消";
        // 清空数组
        [self.address removeAllObjects];
        [self.searchTabelView reloadData];
    } else {
        self.navigationItem.rightBarButtonItem.title = @"删除";
        
        self.searchKey = self.inputField.text;
        [self initPoiSearchWith:self.coordinate];
    }
}

#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP
    [self.inputField resignFirstResponder];
}

/**
 *  移除遮盖
 */
- (void)cancelClick {
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"取消"]) {
        [self.searchTabelView removeFromSuperview];
        [self.inputField resignFirstResponder];
        
        self.searchKey = @"小区";
        
        UIButton *button = self.toolView.subviews[0];
        
        [self buttonClick:button];
        
        // 刷新tableview
        [self initPoiSearchWith:self.coordinate];
    } else {
        self.inputField.text = nil;
        // 清空数组数据
        [self.address removeAllObjects];
        
        // 刷新searchTableView
        [self.searchTabelView reloadData];
        
        self.navigationItem.rightBarButtonItem.title = @"取消";
    }
}
@end
